﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Volo.Abp.Guids;
using Ocean.His.MedicalInsurance.Tool.Models;
using Ocean.His.MedicalInsurance.Data;

namespace Ocean.His.MedicalInsurance
{
    /// <summary>
    /// 基线版
    /// </summary>
    public abstract class MedicalInsuranceBaseProvider : IMedicalInsurance
    {
        protected string _userId;
        protected string _signNo;
        private int _timeoutMinutes = 10;
        private MedicalInsuranceOption _medicalInsuranceOption;
        private IGuidGenerator _guidGenerator;
        public ILogger _logger;

        public MedicalInsuranceBaseProvider(ILogger logger
            , MedicalInsuranceOption medicalInsuranceOption
            , IGuidGenerator guidGenerator)
        {
            _logger = logger;
            _medicalInsuranceOption = medicalInsuranceOption;
            _guidGenerator = guidGenerator;
        }

        /// <summary>
        /// 9001
        /// 签到
        /// </summary>
        /// <returns></returns>
        public virtual Tuple<int, string> SignIn(string ip, string mac, string userId)
        {
            try
            {
                _logger.LogInformation(MedicalInsuranceConst.SIGN_IN_START);
                SI9001RequestModel sI9001RequestModel = new SI9001RequestModel(_medicalInsuranceOption);
                sI9001RequestModel.SetSignInModel(ip, mac, userId);
                sI9001RequestModel.SetMsgId(_guidGenerator.Create().ToString("N"));
                sI9001RequestModel.SetOpter(userId, userId);
                return SiPost(sI9001RequestModel);
            }
            catch (Exception e)
            {
                return new Tuple<int, string>(-1, e.Message);
            }
        }

        /// <summary>
        /// 9002
        /// 签退
        /// </summary>
        /// <returns></returns>
        public virtual Tuple<int, string> SignOut(string userId)
        {
            try
            {
                _logger.LogInformation(MedicalInsuranceConst.SIGN_OUT_START);
                SI9002RequestModel si9002RequestModel = new SI9002RequestModel(_medicalInsuranceOption);
                si9002RequestModel.SetMsgId(_guidGenerator.Create().ToString("N"));
                si9002RequestModel.SetOpter(userId, userId);
                return SiPost(si9002RequestModel);
            }
            catch (Exception e)
            {
                return new Tuple<int, string>(-1, e.Message);
            }
        }

        /// <summary>
        /// 医保Post接口
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="F"></typeparam>
        /// <param name="url"></param>
        /// <param name="requestModel"></param>
        /// <returns></returns>
        public virtual Tuple<int, string> SiPost<T>(T requestModel)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromMilliseconds(_medicalInsuranceOption.Timeout);
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var requestContent = JsonConvert.SerializeObject(requestModel);
                    _logger.LogInformation(requestContent);
                    HttpContent httpContent = new StringContent(requestContent);
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    httpContent.Headers.ContentType.CharSet = "utf-8";
                    var _baseUrl = _medicalInsuranceOption.Ip;
                    HttpResponseMessage response = httpClient.PostAsync(_baseUrl, httpContent).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        string result = response.Content.ReadAsStringAsync().Result;
                        _logger.LogInformation(result);
                        var siBaseResponseModel = JsonConvert.DeserializeObject<SIBaseResponseModel>(result);
                        return new Tuple<int, string>(siBaseResponseModel.Infcode, siBaseResponseModel.Output);
                    }
                    else
                    {
                        _logger.LogError($"SiPost提交失败：{response.ReasonPhrase}");
                        return new Tuple<int, string>(-1, response.ReasonPhrase);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                _logger.LogError(e.StackTrace);
                return new Tuple<int, string>(-1, e.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="initRequestModel"></param>
        /// <returns></returns>
        public virtual Tuple<int, string> Init(InitRequestModel initRequestModel)
        {
            return new Tuple<int, string>(-1, "");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public virtual Tuple<int, string> ChangePIN()
        {
            return new Tuple<int, string>(-1, "");
        }
    }
}
